<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class wilayah extends CI_Controller {
	
	function __construct(){
		parent::__construct();
		//$this->output->enable_profiler(true);
		$this->load->model('wilayah_model');
	}
	
	function index(){
		$this->load->view('wilayah_view');
	}
	
	function grid(){
		$data = $this->wilayah_model->getdata();
		echo $this->wilayah_model->togrid($data['row_data'], $data['row_count']);
	}
	
	function add(){
		$data['ID_WILAYAH'] = '';
		$data['WILAYAH'] = '';
		$data['WLEVEL'] = '';
		$data['REMARK'] = '';
		
		$this->load->view('wilayah_form_view',$data);
	}
	
	function edit($kode){
		$r = $this->wilayah_model->getdataedit($kode);
		
		$data['ID_WILAYAH'] = $r->row()->ID_WILAYAH;
		$data['WILAYAH'] = $r->row()->WILAYAH;
		$data['WLEVEL'] = $r->row()->WLEVEL;
		$data['REMARK'] = $r->row()->REMARK;
		$data['aksi'] = 'edit';
		$this->load->view('wilayah_form_view',$data);
	}
	
	function save($aksi){
		# init
		$status = "";
		$result = false;
		$data['pesan_error'] = '';
		
		# get post data
		foreach($_POST as $key => $value){
			$data[$key] = $value;
		}
		
		//print_r($data);
		//exit;
		
		# rules validasi form
		$this->form_validation->set_rules("ID_WILAYAH", 'Kode', 'trim|required|xss_clean');
		
		# message rules
		$this->form_validation->set_message('required', 'Field %s harus diisi.');

		$data['pesan_error'] = '';
		if ($this->form_validation->run() == FALSE){
			$data["pesan_error"] .= trim(form_error('ID_KPS',' ',' '))==''?'':form_error('ID_KPS',' ',' ').'<br>';
			//$data["pesan_error"] .= trim(form_error('ID_KPS',' ',' '))==''?'':form_error('ID_KPS',' ',' ').'<br>';
		}else{
			if($aksi=="add"){ // add
				$result = !$this->wilayah_model->isExistKode($data['ID_WILAYAH']);
				if ($result){
					$result = $this->wilayah_model->InsertOnDb($data);
				}else{
					$data['pesan_error'] .= 'Sudah terdapat kode dalam database!';
				}
			}else { // edit
				if($data['ID_WIL'] == $data['ID_WIL']){ // jika kode tidak diubah
					$result=$this->wilayah_model->UpdateOnDb($data);
				}else{
					$result = !$this->wilayah_model->isExistKode($data['ID_WILAYAH']);
					if ($result){
						$result=$this->wilayah_model->UpdateOnDb($data);
					}else{
						$data['pesan_error'] .= 'Sudah terdapat kode dalam database!';
					}
				}
			}
		}
		
		if($result){
			echo json_encode(array('success'=>true));
		}else{
			echo json_encode(array('msg'=>$data['pesan_error']));
		}
	}
	
	function delete($kode){
				
		$result = $this->wilayah_model->DeleteOnDb($kode);
		
		if ($result){
			echo json_encode(array('success'=>true));
		} else {
			echo json_encode(array('msg'=>'Data gagal dihapus'));
		}
	}
	
	
	
}